package com.x.utils;

import java.io.StringReader;
import java.util.HashMap;
import java.util.Map;

import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import org.apache.log4j.Logger;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;

public class ReadXmlToSAX {

	private static Logger log = Logger.getLogger(ReadXmlToSAX.class);

	public static ReadSAX tsax = new ReadSAX();

	public static void parse(String protocolXML) {

		try {
			SAXParserFactory saxfac = SAXParserFactory.newInstance();
			SAXParser saxparser = saxfac.newSAXParser();
			saxparser.parse(new InputSource(new StringReader(protocolXML)), tsax);
		} catch (Exception e) {
			log.error(e);
		}
	}

	public static Map<String, String> resolve(String xml) {
		xml = (xml == null || xml.equals(""))
				? "<?xml version=\"1.0\" encoding=\"utf-8\"?><Request><OrderId>fl1351859597223</OrderId><ProductId>100023</ProductId><CompanyId>100022</CompanyId><ChannelId>100141</ChannelId><OrderType>112</OrderType><Denomination>300</Denomination><CardNO>55</CardNO><CardPwd>55555</CardPwd><Amount>30000</Amount><MerPriv>xyjdx_fuck_fuck</MerPriv><VerifyString>pEaZCm2UEomY/MCMLKY8l344x5KQP5H8ZO3af76V3VZ5bh/W7sLUdFtQ/pc5Jhho/DfdWKG4lL03"
						+ "nglSgeYUpzWuR/6PEOGC8oQZ6r+p7jT0VuexuqoYnTAH/EvEx9R8PHjWg5yXKx6nAGJ24Dg/LEjd" + "Q/bPRVgbDiuhKbRzEv4=</VerifyString></Request>"
				: xml;
		parse(xml);
		return tsax.map;
	}
	
	public static void main(String[] args) {
		Map<String, String> m = ReadXmlToSAX.resolve("");
		for (Map.Entry<String, String> entry : m.entrySet()) {
			System.out.println(entry.getKey() + " - " + entry.getValue());
		}
	}
}

class ReadSAX extends DefaultHandler {
	private Logger log = Logger.getLogger(ReadXmlToSAX.class);
	private StringBuffer buf;
	private String str;
	public Map<String, String> map = new HashMap<String, String>();

	public ReadSAX() {
		super();
	}

	public void startDocument() throws SAXException {
		if (this.map != null) {
			this.map.clear();
		}
		buf = new StringBuffer();
		// LogManage.ShowLog("*******开始解析XML*******");
	}

	public void endDocument() throws SAXException {
		// LogManage.ShowLog("*******XML解析结束*******");
	}

	public void endElement(String namespaceURI, String localName, String fullName) throws SAXException {

		str = buf.toString();
		log.info("节点=" + fullName + "\tvalue=" + buf + " 长度=" + buf.length());
		map.put(fullName, str);
		buf.delete(0, buf.length());
	}

	public void characters(char[] chars, int start, int length) throws SAXException {
		// 将元素内容累加到StringBuffer中
		buf.append(chars, start, length);
	}
}
